<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax错误处理</title>
  </head>

  <body>
    <button id="btn">点击发送Ajax</button>
  </body>
  <script>
    let btn = document.querySelector("#btn");
    btn.onclick = () => {
      let xhr = new XMLHttpRequest();
      xhr.open('get', "http://127.0.0.1:3000/error");
      xhr.send();
      xhr.onload = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 400) {
            console.log(xhr.responseText);
          }
        }
      }
      // 发生断网错误时，不会触发onload事件，需要onerror时间处理
      xhr.onerror = function () {
        alert("对不起，断网了！");
      }
    }
  </script>

</html>